package com.li.commons.util;

import java.util.HashMap;

import javax.servlet.http.HttpServletRequest;
/**
 * 获取ipv4地址
 * @author WangZhao
 *
 */
public class IPv4Util {
	
	public static String getRemoteHost(HttpServletRequest request){
	    String ip = request.getHeader("x-forwarded-for");
	    if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
	        ip = request.getHeader("Proxy-Client-IP");
	    }
	    if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
	        ip = request.getHeader("WL-Proxy-Client-IP");
	    }
	    if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
	        ip = request.getRemoteAddr();
	    }
	    return ip.equals("0:0:0:0:0:0:0:1")?"127.0.0.1":ip;
	}
	
	public static String getCityByIp(String ip){
		String cityStr = null;
		//根据ip地址获取城市信息
		String ipCityJson = HttpUtil.sendGet("http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=json&ip="+ip);
		try {
			HashMap resultMap = JsonUtil.jsonToObject(ipCityJson, HashMap.class);
			if(!resultMap.get("ret").toString().equals("-1")){
				String country = (String)resultMap.get("country");
				String province = (String)resultMap.get("province");
				String city = (String)resultMap.get("city");
				cityStr = country +"-"+province+"-"+city;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return cityStr;
	}
}
